import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { DatePicker, Divider, Drawer, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import type { ReserveTableListItem } from './data';
import { findReserveDetail, getReservationList } from './service';
import Index from './components/ReserveDetail';
import {
  CommonSelectionStatus,
  ReservationOrderStatus,
  ReservationPaymentStatusEnum,
} from './utils/utils';
import RefundApply from '@/pages/Reservation/components/RefundApply';

const TableList: React.FC = () => {
  const [detailModalVisible, handledetailModalVisible] = useState<boolean>(false);
  const [detailItemId, setDetailItemId] = useState<string | null>(null);
  const [selectItem, setSelectItem] = useState<ReserveTableListItem | undefined>(undefined);
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [refundVisible, setRefundVisible] = useState<boolean>(false);

  // @ts-ignore
  function onRefund(record: Reservation) {
    setSelectItem(record);
    setRefundVisible(true);
  }

  // @ts-ignore
  const columns: ProColumns<ReserveTableListItem>[] = [
    {
      title: '预约号',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '停车区域',
      dataIndex: 'zoneName',
      hideInSearch: true,
      render: (_, record) => <div>{record.zoneName || '未知'}</div>,
    },
    {
      title: '车位号',
      dataIndex: 'spaceName',
      hideInSearch: true,
      render: (_, record) => <div>{record.spaceName}</div>,
    },
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      hideInSearch: true,
      render: (_, record) => <div>{record.plateNumber}</div>,
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      hideInSearch: false,
      render: (_, record) => <Tag>{record.startDate || '-'}</Tag>,
      renderFormItem: () => <DatePicker.RangePicker showTime format="YYYY-MM-DD HH:mm" />,
      search: {
        transform: (value: string[]) => {
          return { startSearchTime: value[0], endSearchTime: value[1] };
        },
      },
    },
    {
      title: '完成时间',
      dataIndex: 'endDate',
      hideInSearch: true,
      render: (_, record) => {
        return <Tag>{record.endDate || '-'}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'order_status',
      valueEnum: ReservationOrderStatus.valueEnumMap(),
    },
    {
      title: '费用',
      dataIndex: 'total_reserve_fee',
      render: (_, record) => {
        return record?.total_reserve_fee + '元';
      },
    },
    {
      title: '支付状态',
      dataIndex: 'payment_status',
      valueEnum: CommonSelectionStatus.valueEnumMap(ReservationPaymentStatusEnum),
    },
    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onShowDetail = () => {
          handledetailModalVisible(true);
          setDetailItemId(record.id);
        };

        return (
          <div>
            <a onClick={onShowDetail}>详情</a>
            <Divider type={'vertical'} />
            {record.payment_status === 2 && (
              <a
                onClick={() => {
                  onRefund(record);
                }}
              >
                退款
              </a>
            )}
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<ReserveTableListItem>
        headerTitle="预约记录"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<ReserveTableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => []}
        tableAlertRender={() => false}
        rowSelection={false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return getReservationList({ page, pageSize, ...filter });
        }}
        columns={columns}
      />
      <Drawer
        visible={!!detailItemId && detailModalVisible}
        onClose={() => handledetailModalVisible(false)}
        width="30%"
      >
        {!!detailItemId && detailModalVisible && (
          <Index id={detailItemId} request={(id) => findReserveDetail({ id })} />
        )}
      </Drawer>

      {!!selectItem && refundVisible && (
        <RefundApply
          visible={refundVisible}
          item={selectItem}
          setUnVisible={() => {
            setRefundVisible(false);
          }}
          onSuccessful={() => actionRef.current?.reload()}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
